package cn.xin.user.service.impl;

import cn.xin.base.constant.PhoneConstant;
import cn.xin.base.constant.WechatConstant;
import cn.xin.base.jwt.JwtUtils;
import cn.xin.base.jwt.RsaUtils;
import cn.xin.base.jwt.UserInfo;
import cn.xin.base.util.*;
import cn.xin.system.domain.Menu;
import cn.xin.system.mapper.MenuMapper;
import cn.xin.system.mapper.PermissionMapper;
import cn.xin.user.domain.Logininfo;
import cn.xin.user.domain.User;
import cn.xin.user.domain.Wxuser;
import cn.xin.user.dto.AccountLoginDto;
import cn.xin.user.dto.BinderDto;
import cn.xin.user.dto.WechatDto;
import cn.xin.user.mapper.LogininfoMapper;
import cn.xin.user.mapper.UserMapper;
import cn.xin.user.mapper.WxuserMapper;
import cn.xin.user.service.LoginService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Value("${jwt.pri}")
    private String jwtPri;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public AjaxResult account(AccountLoginDto dto) {
        //校验参数
        //获取登录信息
        Logininfo logininfo = logininfoMapper.findByName(dto);
        //查询账号是否存在
        if (logininfo == null){
            throw new BussinessException("账号或密码错误");
        }

        //获取密码
        String password = logininfo.getPassword();
        String password2 = MD5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());
        //判断密码是否正确
        if (!password.equals(password2)){
            throw new BussinessException("账号或密码错误");
        }

        //生成UUID作为key token
        Map<String, Object> result = getMap(logininfo);

        return AjaxResult.me().success(result);
    }

    @Override
    public AjaxResult wechat(WechatDto dto) {
        //调用第二个接口通过 code 获取openid和access_token
        String JSONStr = HttpUtil.httpGet(String.format(WechatConstant.SECOND_INTER, WechatConstant.APPID, WechatConstant.SECRET,dto.getCode()));
        //把JSONStr转换为JSON对象
        JSONObject jsonObject = JSONObject.parseObject(JSONStr);
        //从JSON对象取出openid和access_token
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //通过openid查询wxuser表是否有该用户
        Wxuser wxuser = wxuserMapper.finByOpenId(openid);
        //判断是否有该用户
        if (wxuser != null){
            //有数据就让用户登录，返回logininfo和token
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            //token
            //生成UUID作为key token
            Map<String, Object> result = getMap(logininfo);

            return AjaxResult.me().success(result);
        }
        //没有该用户，就让他绑定手机号，跳转绑定界面，传过去token和openid"?accessToken="+accessToken+"&openId="+openId;
        StringBuilder sb = new StringBuilder();
        sb.append("?accessToken=")
                .append(accessToken)
                .append("&openId=")
                .append(openid);

        return AjaxResult.me().fail("nobinder").setResultObj(sb.toString());
    }

    /**
     * 手机号绑定
     * @param dto
     * @return
     */
    @Override
    public AjaxResult binder(BinderDto dto) {
        // 校验参数

        //获取手机验证码
        String smsCode = (String) redisTemplate.opsForValue().get(String.format(PhoneConstant.REDIS_KEY, dto.getPhone()));
        //判断手机验证码是否过期，是否正确
        if (StringUtils.isBlank(smsCode) || !smsCode.equals(dto.getVerifyCode())){
            throw new BussinessException("验证码有误");
        }

        //调用微信第三个接口，传openid和token
        String JSONStr = HttpUtil.httpGet(String.format(WechatConstant.THIRD_INTER,dto.getAccessToken(),dto.getOpenId() ));
        //转换为JSON对象
        Wxuser wxuser = JSONObject.parseObject(JSONStr, Wxuser.class);

        //根据手机号查询user表是否有该用户
        User user = userMapper.findByPhone(dto.getPhone());

        //登录信息
        Logininfo logininfo = new Logininfo();

        //判断是否有该用户
        if(user == null){
            //没有该用户就添加三张表
            user = dto.getUser();

            //给登录信息表添加
            BeanUtils.copyProperties(user,logininfo);
            logininfo.setType(0);
            logininfo.setDisable(1);
            logininfoMapper.add(logininfo);

            //给user表的LogininfoId添加id
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }

        //有添加到wxuser中
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);


        //登录成功，把logininfo和token传给前端
        logininfo = logininfoMapper.findByUserId(wxuser.getUserId());

        Map<String, Object> result = getMap(logininfo);

        return AjaxResult.me().success(result);

    }

    private Map<String, Object> getMap(Logininfo logininfo) {
        Map<String,Object> result = new HashMap<>();
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader()
                .getResource(jwtPri).getFile());
        UserInfo userInfo = new UserInfo();
        userInfo.setLogininfo(logininfo);
        if (0 == logininfo.getType()) {
            List<String> snList = permissionMapper.findByLogininfoId(logininfo.getId());
            userInfo.setPermissions(snList);
            List<Menu> menus = menuMapper.findByLogininfoId(logininfo.getId());
            userInfo.setMenus(menus);
            result.put("permissions", snList);
            result.put("menus", menus);
        }
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 3000);
        // 将用户的敏感信息 清空
        logininfo.setPassword(null);
        logininfo.setPhone(null);
        result.put("token", token);
        result.put("logininfo", logininfo);
        return result;
    }
//    private Map<String, Object> getMap(Logininfo logininfo) {
//        String token = UUID.randomUUID().toString();
//        //key：token value：logininfo
//        //存到redis中
//        redisTemplate.opsForValue().set(token, logininfo,30, TimeUnit.MINUTES);
//        //一些数据不能被看到，需要清空
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        logininfo.setPhone(null);
//        logininfo.setEmail(null);
//        //将token和logininfo返回给前端
//        Map<String,Object> result = new HashMap<>();
//        result.put("token",token);
//        result.put("logininfo", logininfo);
//        return result;
//    }
}
